#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<string>
#include<cstdio>
#include<cstring>


std::string changeId(const pthread_t& thread_id)
{
    char tid[128];
    snprintf(tid,sizeof(tid),"0x%x",thread_id);
    return tid;
}
void* start_routine(void* args)
{
    std::string threadname = static_cast<const char*>(args);
    //pthread_detach(pthread_self());//设置自己为分离状态
    int cnt = 5;
    while(cnt--)
    {
        printf("%s running ... : %s\n",threadname.c_str(),changeId(pthread_self()).c_str());
        sleep(1);
    }
    return nullptr;
}
void test()
{
    pthread_t tid;
    //新线程创建好后, 主新线程谁先运行不确定, 所以有可能新线程还没来及执行detach主线程已经走到join那阻塞等待了, 所以后来新线程detach好了主线程也不关心了不知道了, 因为主线程在阻塞等待, 所以有可能出现n为0的情况
    pthread_create(&tid,nullptr,start_routine,(void*)"thread 1");
    std::string main_id = changeId(pthread_self());
    pthread_detach(tid);//比较推荐这种分离方法
    printf("main thread running ... new thread id : %s  main thread id : %s\n",changeId(tid).c_str(),main_id.c_str());
    sleep(2);
    int n = pthread_join(tid,nullptr);
    //一个线程默认是joinable的, 如果设置了分离状态, 不能够进行等待了
    printf("result : %d : %s\n",n,strerror(n));
}



__thread int g_val = 100;//添加__thread可以将一个内置类型设置为线程局部存储
void* start_routine1(void* args)
{
    std::string threadname = static_cast<const char*>(args);
    int cnt = 5;
    while(true)
    {
        printf("%s running ... : %s g_val : %d &g_val : 0x%x\n",\
        threadname.c_str(),changeId(pthread_self()).c_str(),g_val,&g_val);
        sleep(1);
        g_val++;
    }
    return nullptr;
}
void test1()
{
    pthread_t tid;
    pthread_create(&tid,nullptr,start_routine1,(void*)"thread 1");
    std::string main_id = changeId(pthread_self());
    pthread_detach(tid);
    printf("main thread running ... new thread id : %s  main thread id : %s\n",changeId(tid).c_str(),main_id.c_str());
    while(true)
    {
        printf("main thread running ... new thread id : %s  main thread id : %s g_val : %d &g_val : 0x%x\n",\
        changeId(tid).c_str(),main_id.c_str(),g_val,&g_val);
        sleep(1);
    }
}
int main()
{
    //test();
    test1();
    return 0;
}